<template>
  <div>
    <div class="container">
      <div class="caption">注册账号</div>
      <div class="admin">
        <span>账号：</span>
        <el-input v-model.trim="username" placeholder="请输入账号" style="width: 25vw" class="button" @change="change1"></el-input>
        <br />
        <span class="tip" v-show="flag1">输入的账号有误，请输入至少3位的数字或字母密码,，不能超过6位</span>
        <br />
        <span>密码：</span>
        <el-input placeholder="请输入密码" v-model.trim="passworld" show-password style="width: 25vw" class="button" @change="change2"></el-input>
        <br />
        <span class="tip" v-show="flag2">输入的密码有误，请输入至少6位的密码</span>
        <br />
        <span>密码：</span>
        <el-input placeholder="请再次密码" show-password style="width: 25vw" class="button" @change="check($event)" v-model.trim="check_passworld"></el-input>
        <span class="tip" v-show="flag3">请输入与上面相同的密码</span>
      </div>
      <el-button type="success" plain @click="register" class="register">立即注册</el-button>
    </div>
  </div>
</template>

<script>
import '@/assets/static/usuali.css'
//导入自己封装好的axios
import axios from '@/utlis/axios.js'

export default {
  data() {
    return {
      username: '', //注册的账号
      passworld: '', //注册的密码
      check_passworld: '',
      flag1: false, //判断输入的错误是否显示
      flag2: false,
      flag3: false,
    }
  },
  methods: {
    //验证账号的
    change1() {
      if (!/^[a-zA-Z0-9]{3,6}$/.test(this.username)) {
        return (this.flag1 = true)
      }
      this.flag1 = false
    },
    // 验证密码的
    change2() {
      if (!/^[a-zA-Z0-9]{6,}$/.test(this.passworld)) {
        return (this.flag2 = true)
      }
      this.flag2 = false
    },
    check() {
      if (this.passworld !== this.check_passworld) {
        return (this.flag3 = true)
      }
      this.flag3 = false
    },
    async register() {
      if ((this.flag1 = this.flag2 = this.flag3 === true) || (this.username === '' && this.passworld === '')) {
        return alert('注册失败')
      }
      const { data: res } = await axios.post('/api/register', { username: this.username, passworld: this.passworld })
      if ((/^注册失败,用户已被注册$/.test(res.message))) {
        return alert(res.message)
      }
      alert(res.message)
      this.$router.push('/login')
      localStorage.setItem('username', this.username)
      localStorage.setItem('passworld', this.passworld)
    },
  },
  created() {},
}
</script>

<style lang="less" scoped>
.container {
  .caption {
    margin: 0 44%;
    padding-top: 1vw;
    font-size: 3vw;
    font-weight: 600;
    color: rgb(46, 141, 87);
  }

  .admin {
    margin: 0 auto;
    width: 30vw;
    .tip {
      color: red;
      font-size: 0.3vw;
      padding-left: 47px;
    }

    .button {
      margin: 0.5vw auto;
    }
  }
  .register {
    margin: 1vw 45%;
  }
}
</style>